package cn.funnymap.lgis.mp.handler;

import cn.funnymap.lgis.file.FileSize;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;

import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 自定义 MyBatis TypeHandler，用于在数据库 long ↔ Java FileSize 之间自动转换。
 * @author wenzf
 * @since 2025/10/20 15:31
 */
@ConditionalOnClass(BaseTypeHandler.class)
@MappedTypes(Long.class)
@MappedJdbcTypes(JdbcType.BIGINT)
public class FileSizeTypeHandler extends BaseTypeHandler<FileSize> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, FileSize parameter, JdbcType jdbcType) throws SQLException {
        // 数据库存储为 long（字节数）
        ps.setLong(i, parameter.getByteSize());
    }
    
    @Override
    public FileSize getNullableResult(ResultSet rs, String columnName) throws SQLException {
        long value = rs.getLong(columnName);
        return rs.wasNull() ? null : new FileSize(value);
    }
    
    @Override
    public FileSize getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        long value = rs.getLong(columnIndex);
        return rs.wasNull() ? null : new FileSize(value);
    }
    
    @Override
    public FileSize getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        long value = cs.getLong(columnIndex);
        return cs.wasNull() ? null : new FileSize(value);
    }
}
